//
//  SAContractViewController.m
//  SAP
//
//  Created by 中矿科技有限公司 on 17/9/11.
//  Copyright © 2017年 中矿科技有限公司. All rights reserved.
//

#import "SAContractViewController.h"
#import "SAContractSearchViewController.h"
#import "SACDetailedViewController.h"
#import "SATransfertSearchViewController.h"

#import "Ltestview.h"
#import "SAConstralCell.h"

#import "OptionsTypeModel.h"
#import "SAConstractListModel.h"

@interface SAContractViewController ()<LtestviewDelegate,UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)Ltestview *ltestView;
@property (nonatomic, assign, getter=isNoResult) BOOL noResult;

@end

static NSString * const cellId = @"SAConstralCell";
@implementation SAContractViewController
{
    AFHTTPData *_http;
    NSMutableArray *_sourceData;
    NSInteger pageIndex;//页数
    NSInteger pageSize;//一页的显示数
    MBProgressHUD *_waitHud;
    NSString *_keyWord;
    BOOL _isPulling;
    NSString *_startTime;
    NSString *_endTime;
    NSMutableArray *_optionTypes;//合同类型
    NSMutableArray *_optionStatus;//合同状态
    NSString *_contractStatus;
    NSString *_contractType;
}

-(Ltestview *)ltestView{
    if (_ltestView) {
        return _ltestView;
    }
    NSMutableArray *typeArray =[NSMutableArray array];
    for (OptionsTypeModel * model  in _optionTypes) {
        [typeArray addObject: model.value];
    }
    NSMutableArray *statusArray =[NSMutableArray array];
    for (OptionsTypeModel * model  in _optionStatus) {
        [statusArray addObject: model.value];
    }
    _ltestView = [[Ltestview alloc]initWithFrame:(CGRect){0,0,SCREEN_WIDTH,48} delegate:self];
    _ltestView.titles =@[@"有限期",@"状态",@"类型"];
    _ltestView.titleDes =@{@"有限期":@[@"今年",@"去年",@"近三年",@"全部"],@"状态":statusArray,@"类型":typeArray};
    UILabel *lable =[[UILabel alloc]initWithFrame:CGRectMake(0, 49, SCREEN_WIDTH, 1)];
    lable.backgroundColor =[UIColor colorFromHex:@"cccccc"];
    [self.view addSubview:lable];
    return _ltestView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _http =[[AFHTTPData alloc]init];
    _optionTypes =[[NSMutableArray alloc]init];
    _optionStatus =[[NSMutableArray alloc]init];
    _sourceData =[[NSMutableArray alloc]init];
    pageIndex =0;
    pageSize =7;
    _contractType =@"-1";
    _contractStatus =@"-1";
    _keyWord =@" ";
    if(!_waitHud)_waitHud=[[MBProgressHUD alloc] initWithView:self.view];//加载
    [self.view addSubview:_waitHud];
    [self groupQueue];

}
//获取合同类型
-(void)groupQueue{
    [_waitHud showAnimated:YES];
     dispatch_queue_t dispatchQueue = dispatch_queue_create("ted.queue.next", DISPATCH_QUEUE_CONCURRENT);
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_enter(group);
    dispatch_group_enter(group);
    
    dispatch_group_async(group, dispatchQueue, ^{
        
        NSString *strUrl =[NSString stringWithFormat:SAPGetOptionsKUrl,@"合同",@"合同类型"];
        [_http postDataWithUrl:[strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]httpBobyData:nil onSuccess:^(NSData *data) {
             dispatch_group_leave(group);
            [_optionTypes addObjectsFromArray:[OptionsTypeModel getGetOptionsTypefromData:data]];

        } onFailure:^(NSError *error) {
             dispatch_group_leave(group);
        }];
    });
    dispatch_group_async(group, dispatchQueue, ^{
        
        
        NSString *strUrl =[NSString stringWithFormat:SAPGetOptionsKUrl,@"合同",@"合同状态"];
        [_http postDataWithUrl:[strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]httpBobyData:nil onSuccess:^(NSData *data) {
            [_optionStatus addObjectsFromArray:[OptionsTypeModel getGetOptionsTypefromData:data]];
            dispatch_group_leave(group);
        } onFailure:^(NSError *error) {
             dispatch_group_leave(group);
        }];
    });
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        [_waitHud showAnimated:NO];
        [_waitHud hideAnimated:YES];
        [self customUI];
        [self pullDown];
        [self pullUp];

    });
}


-(void)customUI
{
    self.navigationItem.title =@"合同管理";
    
   self.navigationItem.rightBarButtonItem =[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"搜索"] style:UIBarButtonItemStylePlain target:self action:@selector(onClickedSearchItem)];
    
    self.tableView =[[UITableView alloc]initWithFrame:CGRectMake(0,49 , SCREEN_WIDTH, SCREEN_HEIGHT-64-48-40)];
    self.tableView.showsHorizontalScrollIndicator =NO;
    self.tableView.showsVerticalScrollIndicator =NO;
    _tableView.separatorStyle =UITableViewCellSeparatorStyleNone;
    [self.tableView registerNib:[UINib nibWithNibName:@"SAConstralCell" bundle:nil] forCellReuseIdentifier:cellId];
    _tableView.backgroundColor =SA_AllBackColor;
    self.tableView.rowHeight =50;
    self.tableView.separatorColor =[UIColor colorWithWhite:0.9 alpha:1];
    self.tableView.delegate =self;
    self.tableView.dataSource =self;
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.ltestView];

    //获取时间
    _startTime =@"1970-01-01";
    _endTime =@"2100-01-01";

}

#pragma mark 刷新界面
-(void)pullDown//下拉页面刷新
{
    __unsafe_unretained __typeof(self) weakSelf = self;
    
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _isPulling = YES;
        [weakSelf loadNewData];
    }];
    
    // 马上进入刷新状态
    [self.tableView.mj_header beginRefreshing];
}
-(void)pullUp//上啦页面刷新
{
    __weak __typeof(self) weakSelf = self;
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _isPulling = NO;
        [weakSelf loadMoreData];
    }];
}
-(void)loadMoreData{
    pageSize +=7;
    [self prepareData:NO];
}
- (void)loadNewData
{
    
    pageSize =7;

    [self prepareData:NO];
    [self.tableView.mj_footer resetNoMoreData];//恢复数据加载
}
-(void)prepareData:(BOOL)update{

    // _waitHud.mode = MBProgressHUDModeText;
    if (update)[_waitHud showAnimated:YES];
    NSMutableDictionary *batchDict =[[NSMutableDictionary alloc]init];
    [batchDict setObject:[NSString stringWithFormat:@"%ld",(long)pageSize] forKey:@"maxResultCount"];
    [batchDict setObject:@"0" forKey:@"skipCount"];
    [batchDict setObject:_contractStatus forKey:@"contractStatus"];
    [batchDict setObject:_contractType forKey:@"contractType"];
    [batchDict setObject:[_startTime stringByAppendingString:@"T00:00:00.000Z" ]forKey:@"startDate"];
    [batchDict setObject:[_endTime stringByAppendingString:@"T23:59:59.000Z"]forKey:@"endDate"];
    
    [_http postTokenDataWithUrl:SAPContractListKUrl httpBobyData:batchDict onSuccess:^(NSData *data) {
        NSArray *array =[SAConstractListModel getGetOptionsListfromData:data];
        if (_isPulling) {
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer resetNoMoreData];
        }else{
            if ([_sourceData count] == [array count]) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                [self.tableView.mj_footer endRefreshing];
            }
        }
        [_sourceData removeAllObjects];
        [_sourceData addObjectsFromArray:array];
        [_tableView reloadData];
        [_waitHud showAnimated:NO];
        [_waitHud hideAnimated:YES];
    } onFailure:^(NSError *error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];

}

#pragma mark UITableView-Deleagte

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _sourceData.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    SAConstralCell *cell =[tableView dequeueReusableCellWithIdentifier:cellId forIndexPath:indexPath];
    cell.selectionStyle =UITableViewCellSelectionStyleNone;
    [cell setFromConstractListModel:_sourceData[indexPath.row]];
    [cell.transferCountBtn addTarget:self action:@selector(onClickedTransferBtn:) forControlEvents:UIControlEventTouchUpInside];
    cell.transferCountBtn.tag =1000+indexPath.row;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    SACDetailedViewController *cDetailedVC =[[SACDetailedViewController alloc]init];
    cDetailedVC.controllerId =[_sourceData[indexPath.row] instanceId];
    cDetailedVC.transferCount =[_sourceData[indexPath.row] transferCount];
    cDetailedVC.completion =^(id userInfo, SACDetailedViewController *bVC){
        [self prepareData:YES];
    };

    [self.navigationController pushViewController:cDetailedVC animated:NO];
}



-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return  183;
}




//Ltestview-Delegate
-(void)clickActionInSection:(NSString *)rowStr2 row:(NSString *)rowStr row3:(NSString *)rowStr3{
    for (OptionsTypeModel *model in _optionStatus) {
        if ([model.value isEqualToString:rowStr2]) {
            _contractStatus =model.key.description;
        }
    }
    for (OptionsTypeModel *model in _optionTypes) {
        if ([model.value isEqualToString:rowStr3]) {
            _contractType =model.key.description;
        }
    }
    
    if ([rowStr isEqualToString:@"今年"]){
        [NSString getYearStatus:SAPCurrentYear yearTime:^(NSString *firstDay, NSString *lastDay) {
            _startTime =firstDay ;
            _endTime =lastDay ;
        }];
    }else if ([rowStr isEqualToString:@"去年"]){
        [NSString getYearStatus:SAPCurrentLastYear yearTime:^(NSString *firstDay, NSString *lastDay) {
            _startTime =firstDay ;
            _endTime =lastDay ;
        }];
    }else if ([rowStr isEqualToString:@"近三年"]){
        [NSString getYearStatus:SAPNearThreeYear yearTime:^(NSString *firstDay, NSString *lastDay) {
            _startTime =firstDay ;
            _endTime =lastDay ;
        }];
    }else if ([rowStr isEqualToString:@"全部"]){
        _startTime =@"1970-01-01";
        _endTime =@"2100-01-01";
    }
    

    [self prepareData:YES];
}


-(void)onClickedSearchItem{
    UITabBarController * nav  = (UITabBarController*)self.mm_drawerController.centerViewController;
    
    UINavigationController *vc =  nav.viewControllers[1];
    
    SAContractSearchViewController *SACsearchVC =[[SAContractSearchViewController alloc]init];
    [vc pushViewController:SACsearchVC animated:NO];
}

-(void)onClickedTransferBtn:(UIButton *)sender{
    if([_sourceData[sender.tag-1000] transferCount].integerValue ==0) {
        [MBProgressHUD showSuccess:@"该合同暂无调拨单"];
        return;
    }
    SATransfertSearchViewController *saTransferSVC =[[SATransfertSearchViewController alloc]init];
    saTransferSVC.contractId =[_sourceData[sender.tag-1000] Id].description;
    [self.navigationController pushViewController:saTransferSVC animated:NO];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
